<template>
  <div class="login-container">
    <img src="../../assets/bg.png" class="bg-img" />
    <div class="center">
      <div class="left">
        <img src="../../assets/bg_left.png" class="left-bg-img" />
      </div>
      <div class="right">
        <div class="login-tab">
          <div class="code-info">
            <template v-if="isAccountLogin">
              <img src="../../assets/dingding.png" />
              <span>使用钉钉扫码</span>
            </template>
            <span v-else>账号密码登录</span>
          </div>
          <div class="img-w" @click="isAccountLogin = !isAccountLogin">
            <img v-if="isAccountLogin" class="code-pic" src="../../assets/code.png" />
            <img v-else class="code-pic" src="../../assets/loginpwd.png" />
          </div>
        </div>
        <!-- 账密登录 -->
        <div class="form-wrapper" v-if="isAccountLogin">
          <div v-if="showFixedCompany" class="title">欢迎登录 {{ formInfo.companyName }}管理系统</div>
          <div v-else class="title">欢迎登录 顾本ERP</div>
          <a-form ref="formRef" :model="formInfo" class="mt-8">
            <a-form-item v-if="!showFixedCompany" field="companyName" hide-label :rules="[{ required: true, message: '请输入/或选择公司名称' }]" :validate-trigger="['change', 'input']">
              <a-select v-model="formInfo.companyName" placeholder="请输入/或选择公司名称" allow-create allow-clear size="large">
                <template #prefix>
                  <icon-common />
                </template>
                <a-option v-for="item in companyList" :key="item" :label="item" :value="item" />
              </a-select>
            </a-form-item>
            <a-form-item field="username" hide-label :rules="[{ required: true, message: '请输入用户名/手机号' }]" :validate-trigger="['change', 'input']">
              <a-input v-model="formInfo.username" placeholder="请输入用户名/手机号" allow-clear size="large">
                <template #prefix>
                  <icon-mobile />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item field="password" hide-label :rules="[{ required: true, message: '请输入密码' }]" :validate-trigger="['change', 'input']">
              <a-input-password v-model="formInfo.password" placeholder="请输入密码" allow-clear size="large" autocomplete>
                <template #prefix>
                  <icon-lock />
                </template>
              </a-input-password>
            </a-form-item>
          </a-form>
          <div class="mt-10">
            <a-button type="primary" size="large" class="login" :loading="loading" @click="onLogin"> 登录 </a-button>
          </div>
        </div>
        <!-- 钉钉登录 -->
        <div class="dd-code-con" v-else>
          <template v-if="scanCodeState === 1">
            <h2>
              <img src="../../assets/dingding.png" />
              <span>钉钉扫码登录</span>
            </h2>
            <a-spin :loading="codeLoading" style="height: 310px">
              <div id="dingdingLoginCode"></div>
            </a-spin>
            <div class="flex-c-c">
              <p style="color: #999; margin-right: 5px">刷新二维码</p>
              <icon-refresh :size="16" class="highlight cursor" @click="initDingDingCode" />
            </div>
          </template>
          <!-- 未注册 -->
          <div v-if="scanCodeState === 0" class="unregistered">
            <a-empty>
              <template #image>
                <icon-exclamation-circle-fill />
              </template>
              <p style="font-size: 20px">钉钉小程序未授权</p>
            </a-empty>
          </div>
          <!-- 多租户 -->
          <div v-if="scanCodeState === 2" class="choose-company-wrap">
            <h4>请选择登录公司</h4>
            <p>以下为你已加入的公司</p>
            <a-scrollbar style="height: 320px; overflow: auto">
              <ul class="company-list">
                <li class="flex-c-sb" v-for="(item, i) in ddCompanyList" :key="i" @click="loginByDD(item)">
                  <div class="flex-c">
                    <a-avatar :size="44" shape="square">
                      <icon-bar-chart />
                    </a-avatar>
                    <p class="company-name">{{ item.companyShortName }}</p>
                  </div>
                  <icon-arrow-right />
                </li>
              </ul>
            </a-scrollbar>
          </div>
          <div class="dd-login-loading" v-show="loading">
            <icon-loading :size="30" />
            <p>正在登录中,请稍后...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'Login',
  })
</script>

<script setup lang="ts">
  import { defineComponent, ref, onMounted, watch, nextTick } from 'vue'
  import { Form } from '@arco-design/web-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'
  import { parseJson } from '@/utils'
  import { pwdEncrypt, pwdEncryptByMd5 } from '@/utils/encrypt'
  import { loginByPwd, getCompanyByCode, loginByAuthCode } from '@/api/login'

  const formInfo = ref<any>({
    username: '',
    password: '',
    companyName: '',
  })
  const loading = ref(false)
  const showFixedCompany = ref(false)
  const companyList = ref<Array<string>>([])
  const router = useRouter()
  const isAccountLogin = ref(true)
  const route = useRoute()
  const userStore = useUserStore()
  const formRef = ref<typeof Form>()
  const ddCompanyList = ref<Array<any>>([]) //钉钉号绑定组织
  const scanCodeState = ref(2) //扫码状态  1扫码状态0未注册2多租户选择
  const codeLoading = ref(false)

  onMounted(async () => {
    formInfo.value.username = window.localStorage.getItem('username')
    let companyId = route.query.id
    if (!companyId) {
      getCompanyList()
      showFixedCompany.value = false
    } else {
      let res: any = await getCompanyByCode({ code: companyId })
      if (res?.data?.companyShortName) {
        formInfo.value.companyName = res.data.companyShortName
        showFixedCompany.value = true
      } else {
        getCompanyList()
        showFixedCompany.value = false
      }
    }
  })
  //通过钉钉授权码获取组织信息
  async function getCompanyByDD(DDcode: any) {
    loading.value = true
    let res: any = await loginByAuthCode({
      authCode: DDcode,
    })
    if (!res) {
      loading.value = false
      initDingDingCode()
      return
    }
    ddCompanyList.value = res?.data?.orgInfos || []
    if (!ddCompanyList.value.length) {
      // 未返回组织说明未注册
      scanCodeState.value = 0
      loading.value = false
    } else if (ddCompanyList.value.length === 1) {
      // 只有一个组织自动登录
      await loginByDD(ddCompanyList.value[0])
    } else {
      // 多个组织需要选择
      scanCodeState.value = 2
      loading.value = false
    }
  }
  // 根据租户信息登录-钉钉
  async function loginByDD(item: any) {
    loading.value = true
    let res: any = await loginByPwd({
      companyName: item.companyShortName,
      loginName: item.loginName,
      pwd: await pwdEncryptByMd5(item.password),
    })
    if (!res?.data) {
      loading.value = false
      return
    }
    loginSuccess(res.data, item.companyShortName, item.loginName)
  }
  // 开始登录
  async function onLogin() {
    const valid = await formRef.value?.validate()
    if (valid) return false
    loginRequest()
  }
  // 账密登录请求
  async function loginRequest() {
    loading.value = true
    let res: any = await loginByPwd({
      companyName: formInfo.value.companyName,
      loginName: formInfo.value.username,
      pwd: await pwdEncrypt(formInfo.value.password),
    })
    if (!res?.data) {
      loading.value = false
      return
    }
    loginSuccess(res.data, formInfo.value.companyName, formInfo.value.username)
  }
  // 登录成功
  async function loginSuccess(data: any, companyName: string, username: string) {
    let resp = await userStore.initUser(data.token, data.result)
    if (!resp) {
      loading.value = false
      return
    }
    // 需要缓存登录成功之后的公司名
    let _index = companyList.value.indexOf(companyName)
    if (_index > -1) {
      companyList.value.splice(_index, 1)
    }
    companyList.value.unshift(companyName)
    window.localStorage.setItem('companyList', JSON.stringify(companyList.value))
    window.localStorage.setItem('loginName', username)
    router
      .replace({
        path: route.query.redirect ? (route.query.redirect as string) : '/',
      })
      .then(() => {
        Message.success('登录成功，欢迎：' + username)
      })
    setTimeout(() => {
      loading.value = false
    }, 2000)
  }
  // 获取缓存的公司列表
  function getCompanyList() {
    let _companyList = window.localStorage.getItem('companyList')
    companyList.value = parseJson(_companyList, [])
    formInfo.value.companyName = companyList.value?.[0]
  }
  // 生成钉钉二维码
  function initDingDingCode() {
    // 二维码加载有延迟，加一个loading
    codeLoading.value = true
    setTimeout(() => {
      codeLoading.value = false
    }, 1000)
    let _redirect = encodeURIComponent(window.location.origin)
    window.DTFrameLogin(
      {
        id: 'dingdingLoginCode',
        width: 300,
        height: 300,
      },
      {
        redirect_uri: _redirect,
        client_id: 'suitea6bqqeeg5voaotmr',
        scope: 'openid',
        response_type: 'code',
        prompt: 'consent',
      },
      (loginResult: any) => {
        const { redirectUrl, authCode } = loginResult
        // 这里可以直接进行重定向
        // window.location.href = redirectUrl
        if (loading.value) return
        getCompanyByDD(authCode)
      },
      (errorMsg: any) => {
        // 失败原因
        alert(`Login Error: ${errorMsg}`)
      }
    )
  }

  watch(
    () => isAccountLogin.value,
    (newVal) => {
      if (!newVal) {
        scanCodeState.value = 1
        //重新钉钉二维码
        nextTick(() => {
          initDingDingCode()
        })
      }
    }
  )
</script>

<style lang="less" scoped>
  @leftWith: 35%;
  .login-container {
    position: relative;
    overflow: hidden;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
    .bg-img {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    .bottom {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 3%;
      font-size: 14px;
      font-weight: bold;
      color: #333;
      text-align: center;
    }
    .center {
      position: relative;
      z-index: 9;
      width: 70%;
      height: 60%;
      border-radius: 10px;
      border: 1px solid #f5f5f5;
      display: flex;
      align-items: center;
      background-color: #fff;
      box-shadow: 0 0 5px #ececec;
      .right {
        position: relative;
        width: 50%;
        padding: 5% 5% 2%;
        height: 100%;
        display: flex;
        flex-direction: column;
      }
      .login-tab {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .code-info {
          height: 24px;
          margin-right: 10px;
          display: flex;
          align-items: center;
          img {
            width: 14px;
            height: 14px;
            margin-right: 8px;
          }
          span {
            color: #838a9d;
            font-size: 14px;
            line-height: 1;
          }
        }
        .code-pic {
          width: 56px;
          height: 56px;
          cursor: pointer;
        }
      }
      .left {
        position: relative;
        width: 50%;
        height: 100%;
        padding: 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        text-align: center;
        .left-bg-img {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }
        .proj-name {
          font-size: 30px;
          font-weight: bold;
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .form-wrapper {
        .title {
          font-size: 25px;
          font-weight: bold;
          margin-bottom: 20px;
          text-align: center;
        }
        .login {
          width: 100%;
        }
      }
    }

    @media screen and(max-width: 966px) {
      .left {
        display: none;
      }
      .right {
        background-image: url('../../assets/img_login_mobile_bg_01.jpg');
        background-size: cover;
        .form-wrapper {
          width: 80% !important;
        }
      }
    }
  }
  .dd-code-con {
    position: relative;
    text-align: center;
    h2 {
      color: #3c4353;
      font-weight: bold;
      font-size: 20px;
      line-height: 30px;
      img {
        width: 22px;
        height: 22px;
        vertical-align: middle;
        margin-right: 8px;
      }
    }
    .dd-login-loading {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(255, 255, 255, 0.9);
      text-align: center;
      padding-top: 35%;
      color: #1966ff;
    }
  }
  .unregistered {
    width: 300px;
    margin: 40px auto;
  }
  .choose-company-wrap {
    text-align: left;
    h4 {
      margin-bottom: 5px;
      font-size: 20px;
      font-weight: bold;
    }
  }
  .company-list {
    width: 350px;
    margin: 0 auto;
    max-height: 300px;
    li {
      background-color: #eee;
      border-radius: 6px;
      margin-top: 10px;
      padding: 8px 15px 8px 8px;
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        transform: translateX(3px);
      }
      .arco-avatar {
        background-color: rgb(var(--primary-3));
        margin-right: 10px;
      }
    }
  }
</style>
